/*
 * @author zzr
 * @date: 2025/10/18  10:46
 * @description: 在二叉搜索树中找到树中的两个指定节点的最近公共祖先
 */
public class Demo28 {

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) return null;
        // 如果根节点和 p 或 q 相同，则根节点一定是最近公共祖先
        if (root == p || root == q) {
            return root;
        }
        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right,p,q);

        // 如果左右子树都有值，则公共祖先为 root
        if (left != null && right != null) {
            return root;
        } else if (left != null) { // 左子树不为空，右子树为空
            // 则说明 p 和 q 都在左子树中
            return left;
        } else {
            return right;
        }
    }
}
